﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataAccess
{
    public static class DA
    {
        static SqlConnection Conn = null;
        static SqlCommand cmd = null;
        static SqlDataAdapter sda = null;
        static DataTable dt = null;

        static DA()
        {
            Conn = new SqlConnection();
            Conn.ConnectionString = ConfigurationManager.ConnectionStrings["ServerName"].ToString();
            cmd = new SqlCommand();
            cmd.Connection = Conn;
        }

        public static DataTable GetDataTable(string query, CommandType commandType, string[] paras, object[] values)
        {
            dt = new DataTable();
            if (Conn.State != ConnectionState.Open)
                Conn.Open();
            cmd.CommandText = query;
            cmd.CommandType = commandType;
            if (paras != null)
            {
                for (int i = 0; i < paras.Length; i++)
                {
                    cmd.Parameters.AddWithValue(paras[i], values[i]);
                }
            }
            sda = new SqlDataAdapter(cmd);
            sda.Fill(dt);
            cmd.Parameters.Clear();
            Conn.Close();
            return dt;
        }

        public static int ExcuteSql(string query, CommandType commandType, string[] paras, object[] values)
        {
            int res = 0;
            if (Conn.State != ConnectionState.Open)
                Conn.Open();
            cmd.CommandText = query;
            cmd.CommandType = commandType;
            if (paras != null)
            {
                for (int i = 0; i < paras.Length; i++)
                {
                    cmd.Parameters.AddWithValue(paras[i], values[i]);
                }
            }
            res = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            Conn.Close();
            return res;
        }

        public static object GetOneData(string query, CommandType commandType, string[] paras, object[] values)
        {
            object obj = null;
            if (Conn.State != ConnectionState.Open)
                Conn.Open();
            cmd.CommandText = query;
            cmd.CommandType = commandType;
            if (paras != null)
            {
                for (int i = 0; i < paras.Length; i++)
                {
                    cmd.Parameters.AddWithValue(paras[i], values[i]);
                }
            }
            obj = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            Conn.Close();
            return obj;
        }
    }
}
